<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="客户端密钥管理" width="700px" destroyOnClose>
    <BasicForm @register="registerForm" />

    <template #footer>
      <a-button @click="handleSubmit(false)" type="primary" v-if="!isSetting && !isDetail">生成</a-button>
      <a-button @click="handleSubmit(true)" type="primary" v-else-if="!isDetail">变更</a-button>
      <a-button @click="closeModal">取消</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { Modal } from "ant-design-vue"
  import { secretFormSchema } from "../data"
  import { settingSecret, getSecret } from "../api"

  const emit = defineEmits(["register", "success"])
  const isSetting = ref(false)
  const isDetail = ref(false)
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: secretFormSchema,
    labelWidth: 120,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    await resetFields()
    setModalProps({ confirmLoading: false })
    isSetting.value = !!data.record?.isSettingSecret
    isDetail.value = !!data?.isDetail
    await setFieldsValue({ ...data.record })
  })

  async function handleSubmit(v) {
    const doSubmit = async () => {
      try {
        setModalProps({ loading: true })
        let values = await validate()
        setModalProps({ confirmLoading: true })
        const clientDetail = await settingSecret(values)
        await setFieldsValue({ ...clientDetail })
        isSetting.value = true
        emit("success", clientDetail)
      } finally {
        setModalProps({ loading: false })
      }
    }
    if (v) {
      Modal.confirm({
        title: "确认变更？",
        content: "变更之后, 当前客户端版本将被升级, 使用方需要替换客户端版本才能使用, 历史版本依旧可以使用",
        okText: "确认",
        cancelText: "取消",
        onOk: () => {
          doSubmit()
        },
      })
      return
    }
    doSubmit()
  }
</script>
